package com.ytrsoft.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import com.ytrsoft.response.ResponseEntity;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;


@RestController
@RequestMapping("/file")
@Tag(name = "文件接口")
public class FileController {

    @Value("${file.upload-dir}")
    private String uploadDir;

    @PostMapping("/upload")
    @Operation(summary = "文件上传")
    public ResponseEntity<String> upload(@RequestParam("file") MultipartFile file) {
        String filename = file.getOriginalFilename();
        String extName = FileUtil.extName(filename);
        String fileId = UUID.randomUUID().toString();
        Path fileParent = Paths.get(uploadDir, extName);
        Path filePath = fileParent.resolve(fileId + "." + extName);
        try {
            Files.createDirectories(fileParent);
            file.transferTo(filePath);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String url = "/" + extName + "/" + fileId;
        return ResponseEntity.succeed(url);
    }

    @GetMapping("/preview/{extName}/{fileName}")
    @Operation(summary = "文件预览")
    public ResponseEntity<Void> preview(HttpServletRequest request, HttpServletResponse response, @PathVariable String extName, @PathVariable String fileName) {
        String latestName = fileName + "." + extName;
        Path fileParent = Paths.get(uploadDir, extName);
        Path filePath = fileParent.resolve(latestName);
        response.setContentType(request.getContentType());
        response.setHeader("Content-Disposition", "inline; filename=" + latestName);
        try {
            File file = filePath.toFile();
            ServletOutputStream out = response.getOutputStream();
            IoUtil.copy(new FileInputStream(file), out);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return ResponseEntity.succeed();
    }

}